var app = getApp();
var config = app.globalData.config;
var util = require('../../utils/util.js');
var QQMapWX = require('../../utils/qqmap-wx-jssdk.min.js');
Page({
  /**
   * 页面的初始数据
   */
  data: {
    isShowMode: false,
    isShowTime: false,
    isShowRemark: false,
    isCheckedHigh: false,
    isShowPoints: false,
    isShowExchange: false,
    items: [{
      title: null,
      number: 1,
      photo: config.defaultCover,
      index: null,
      error: null
    }],
    prizeArray: [],
    selectPrize: {},
    exchangeArray: [],
    selectExchange: {},
    minHour: 10,
    maxHour: 20,
    minDate: new Date().getTime(),
    maxDate: new Date().setDate(new Date().getDate() + 7),
    selectTime: util.formatTime(new Date().setMinutes(new Date().getMinutes() + 15)),
    currentDate: new Date().getTime(),
    weekday: util.getWeekText(new Date().getDay()),
    maxNumber: 20,
    maxPeople: 100,
    title: null,
    people: 1,
    remarks: '',
    userInfo: null,
    points: null,
    location: {
      code: '',
      name: '不限区域'
    },
    address: '',
    uploadCount: 0
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var that = this;
    var {
      high
    } = options;
    !!high && that.setData({
      isCheckedHigh: !!high
    })
    //获取当前位置
    // wx.getLocation({
    //   type: 'gcj02',
    //   success(res) {
    //     const latitude = res.latitude;
    //     const longitude = res.longitude;
    //     that.mygetLocation(latitude, longitude);
    //   }
    // });
    var userInfo = wx.getStorageSync('sUserInfo');
    if (!userInfo) {
      // wx.reLaunch({
      //   url: '/pages/me/me',
      // })
      wx.showToast({
        title: '请授权',
        icon: 'none'
      })
    }
    var prizes = wx.getStorageSync("prizes");
    var exchanges = wx.getStorageSync("exchanges");
    this.setData({
      prizeArray: prizes,
      selectPrize: prizes[0],
      exchangeArray: exchanges,
      selectExchange: exchanges[1],
      userInfo: userInfo
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    var this_ml = this.data.items;
    for (var i = 0; i < this_ml.length; i++) {
      var img = wx.getStorageSync(i + 'photo');
      if (img.length > 0) {
        this_ml[i]['index'] = i;
        this_ml[i]['photo'] = img;
        wx.removeStorageSync(i + 'photo');
      }
    }
    this.setData({
      items: this_ml
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },
  /**
   * 更换图片
   */
  onUploadPhoto(e) {
    var index = e.currentTarget.dataset.index;
    wx.chooseImage({
      count: 1, // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success(res) {
        var filesize = res.tempFiles[0].size;
        if (filesize <= 2000000) {
          const src = res.tempFilePaths[0]
          wx.navigateTo({
            url: '/pages/upload/upload?src=' + src + '&index=' + index
          })
        } else {
          wx.showToast({
            title: '图片不能大于2M',
            icon: 'none'
          })
        }
      }
    })
  },
  /**
   * 开奖时间 显隐并选择
   */
  onClickTime() {
    this.setData({
      isShowTime: true
    });
  },
  onCloseTime() {
    this.setData({
      isShowTime: false
    });
  },
  onConfirmTime(event) {
    this.setData({
      selectTime: util.formatTime(new Date(event.detail)),
      isShowTime: false
    });
  },
  onChangeTime(e) {
    var arr_this = e.detail.getValues().map((x, i) => {
      var v = x * 1;
      if (i == 1) {
        v -= 1;
      }
      return v;
    })
    var selectdt = new Date(...arr_this);
    this.setData({
      weekday: util.getWeekText(selectdt.getDay())
    })
  },
  /**
   * 开奖模式 显隐并选择
   */
  onClickMode() {
    this.setData({
      isShowMode: true
    });
  },
  onCloseMode() {
    this.setData({
      isShowMode: false
    });
  },
  onConfirmMode(e) {
    var mode = e.detail.value;
    this.setData({
      selectPrize: mode,
      isShowMode: false
    });
  },
  /**
   * 兑奖模式 显隐并选择
   */
  onClickExchange() {
    this.setData({
      isShowExchange: true
    });
  },
  onCloseExchange() {
    this.setData({
      isShowExchange: false
    });
  },
  onConfirmExchange(e) {
    var mode = e.detail.value;
    this.setData({
      selectExchange: mode,
      isShowExchange: false
    });
  },
  /**
   * 开奖说明 显隐并赋值
   */
  onClickRemark() {
    this.setData({
      isShowRemark: true
    });
  },
  onBlurRemark(e) {
    this.setData({
      isShowRemark: false,
    });
  },
  onChangeRemark(e) {
    this.setData({
      remarks: e.detail
    });
  },
  /**
   * 移除活动小项
   */
  onRemoveItem(e) {
    var index = (e.currentTarget.id || 0) * 1;
    var this_ml = this.data.items;
    this_ml.splice(index, 1);
    this.setData({
      items: this_ml
    })
    wx.showToast({
      title: '移除成功',
      icon: 'none'
    })
  },
  /**
   * 添加活动小项
   */
  onAddItem() {
    var item = {
      title: null,
      number: 1,
      photo: config.defaultCover,
      index: null,
      error: null
    };

    var this_ml = this.data.items;
    if (this_ml.length == 10) {
      wx.showToast({
        title: '最多添加10个奖品',
        icon: 'none'
      })
      return;
    }
    this_ml.push(item);
    this.setData({
      items: this_ml
    })
  },
  /**
   * 获取输入框的值
   */
  onChangePeople(e) {
    this.setData({
      people: e.detail
    })
  },
  onBlurForm(e) {
    let index = e.target.dataset.index;
    let attr = e.target.dataset.attr;
    let value = attr === 'number' ? e.detail : e.detail.value;
    let this_ml = this.data.items;
    this_ml[index][attr] = value;
  },
  /**
   * 活动主题
   */
  onInputTitle(e) {
    this.setData({
      title: e.detail
    })
  },
  /**
   * 发布活动
   */
  onPush(e) {
    var that = this;
    var errorNumber = 0;
    var this_ml = this.data.items;
    this_ml.forEach(i => {
      if (!i.title) {
        i.error = '奖品名称必填'
        errorNumber++;
      } else {
        i.error = null;
      }
    });
    if (errorNumber > 0) {
      that.setData({
        items: this_ml
      })
      wx.showToast({
        title: '奖品名称必填',
        icon: 'none'
      })
      return;
    }
    if (!that.data.title) {
      wx.showToast({
        title: '活动主题必填',
        icon: 'none'
      })
      return;
    }
    if (that.data.selectPrize.code === 'ToTime' && (new Date(that.data.selectTime) < new Date())) {
      wx.showToast({
        title: '活动时间不能小于当前时间',
        icon: 'none'
      })
      return;
    }
    wx.showLoading({
      title: '发布活动中',
      mask: true
    })
    var activity = {
      title: that.data.title,
      prizeModelCode: that.data.selectPrize.code,
      drawModelCode: null,
      exchangeModelCode: that.data.selectExchange.code,
      openTime: that.data.selectPrize.code === 'ToTime' ? that.data.selectTime : util.formatTime(new Date(), 7),
      openCount: that.data.selectPrize.code === 'ToNum' ? that.data.people : 0,
      userId: that.data.userInfo.id,
      location: that.data.location.code + "|" + that.data.location.name,
      points: that.data.points || 0,
      isHome: that.data.isCheckedHigh ? 1 : 0,
      remark: that.data.remarks,
      address: that.data.address
    };
    var activityDetails = [];
    that.data.items.forEach(i => {
      activityDetails.push({
        title: i.title,
        number: i.number,
        url: i.photo,
        index: i.index
      });
    })
    var acticityRich = [];
    var iit = wx.getStorageSync('iit');
    if (!!iit.ftext) {
      acticityRich.push({
        index: -1,
        text: iit.ftext
      })
    }
    if (!!iit) {
      iit.imgs.forEach(i => {
        acticityRich.push({
          index: i.index,
          text: i.text
        })
      })
    }
    var model = {
      activity: activity,
      details: activityDetails,
      graphics: acticityRich,
      formId: e.detail.formId
    };
    console.log(JSON.stringify(model))
    wx.request({
      url: config.pushUrl,
      method: "POST",
      header: {
        "Content-Type": "application/json"
      },
      data: model,
      success: function(resp) {
        if (resp.data.result == 1) {
          resp.data.data.list.forEach(i => {
            if (i.index != null) {
              var this_item = that.data.items.find(x => x.index == i.index);
              this_item && that.onUploadImg(this_item.photo, i.id);
            }
          })
          resp.data.data.graphics.forEach(i => {
            if (i.index != null) {
              var this_item = iit.imgs.find(x => x.index == i.index);
              this_item && that.onUploadRich(this_item.img, i.id);
            }
          })
          setTimeout(function() {
            wx.removeStorageSync('iit');
            wx.redirectTo({
              url: '/pages/detail/detail?activityId=' + resp.data.data.id,
            })
          }, 3000)
        }
      },
      fail: function() {
        wx.showToast({
          title: '发布失败',
          icon: 'none'
        })
      },
      complete: function() {
        setTimeout(function() {
          wx.hideLoading();
        }, 3000)
      }
    })
  },
  /**
   * 上传图片
   */
  onUploadImg(path, id) {
    wx.uploadFile({
      url: config.uploadImgUrl,
      filePath: path,
      name: 'files',
      formData: {
        id: id
      },
      success: function(res) {
        console.log("上传成功");
        console.log(res)
      },
      fail: function(res) {
        console.log("上传失败，调用接口删除当前数据，并重新发布")
      },
      complete: function(res) {},
    })
  },
  /**
   * 上传图文
   */
  onUploadRich(path, id) {
    var that = this;
    wx.uploadFile({
      url: config.uploadRichUrl,
      filePath: path,
      name: 'files',
      formData: {
        id: id
      },
      success: function(res) {
        if (res.data.result == 1) {

        }
        console.log("上传成功");
        console.log(res)
      },
      fail: function(res) {
        console.log("上传失败，调用接口删除当前数据，并重新发布")
      },
      complete: function(res) {},
    })
  },
  /**
   * 开启高级版
   */
  onHigh(e) {
    var that = this;
    if (e.detail) {
      wx.request({
        url: config.canPushUrl,
        method: "GET",
        header: {
          "Content-Type": "application/x-www-form-urlencoded"
        },
        data: {
          userId: this.data.userInfo.id
        },
        success: function(resp) {
          if (resp.data.code == "200") {
            switch (resp.data.data) {
              case 0:
                wx.showToast({
                  title: '今日推荐位已售完',
                  icon: 'none'
                })
                break;
              case 1:
                that.setData({
                  isCheckedHigh: e.detail,
                  maxNumber: 200,
                  maxPeople: 1000
                });
                wx.showModal({
                  content: '奖品个数上限200，活动人数上限1000',
                  showCancel: false
                })
                break;
              case 2:
                wx.navigateTo({
                  url: '/pages/high/high'
                })
                break;
            }
          }
        },
        fail(res) {},
        complete(res) {}
      })
    } else {
      that.setData({
        isCheckedHigh: e.detail,
        maxNumber: 20,
        maxPeople: 100
      });
    }
  },
  /**
   * 幸运值显隐
   */
  onPoints() {
    this.setData({
      isShowPoints: true
    })
  },
  onClosePoints() {
    this.setData({
      isShowPoints: false
    })
  },
  onPointsAll() {
    this.setData({
      points: this.data.userInfo.points,
      isShowPoints: false
    })
  },
  onChangePoints(e) {
    var points = this.data.userInfo.points;
    points = points < e.detail ? points : e.detail;
    this.setData({
      points: points
    })
  },
  /**
   * 获取定位的详细信息
   */
  mygetLocation: function(latitude, longitude) {
    var that = this;
    var qqmapsdk = new QQMapWX({
      key: config.qqmapKey
    });
    qqmapsdk.reverseGeocoder({
      location: {
        latitude,
        longitude
      },
      success: function(res) {
        var res = res.result;
        that.setData({
          location: {
            code: res.ad_info.adcode,
            name: res.ad_info.district
          }
        })
      },
      fail: function(error) {
        console.error(error);
      }
    })
  },
  /**
   * 选择区域
   */
  onLocation() {
    var that = this;
    wx.chooseLocation({
      success: res => {
        const latitude = res.latitude;
        const longitude = res.longitude;
        that.mygetLocation(latitude, longitude);
      }
    })
  },
  /**
   * 兑奖地址
   */
  onWxAddress() {
    var that = this;
    wx.chooseAddress({
      success(res) {
        that.setData({
          address: res.provinceName + res.cityName + res.countyName + res.detailInfo
        })
      }
    });
  },
  onChangeAddress(e) {
    this.setData({
      address: e.detail
    })
  }
})